Skip to content

[AI-3857] Bill a transcription's unsettled audio at each renewal - #2551

Merged
kanat merged 11 commits into
mainfrom
kanat/ai-3857-bill-unsettled-audio-at-renewal
Nov 26, 2026
Merged

kanat merged 11 commits into
mainfrom
kanat/ai-3857-bill-unsettled-audio-at-renewal

Conversation

@kanat

@kanat kanat commented Nov 26, 2026 •

Copy link
Copy Markdown
Collaborator

Why

A transcription on a vendor the router measures (the vendor bills every second it hears) wrote its usage row at each settled turn and at close. A stream that settles no turn, a long silence say, wrote nothing until it closed, so the balance did not fall while it ran and the lease renewal's money check (#2403) never refused it. Detail: AI-3857.

How it works

lease tick (every LeaseRenew)
 ├─ settle, while a minute of the lease's model costs anything:
 │  session.billUnsettled(nil)
 │    └─ whole ms taken since the last row -> one row
 │       (same row as at close: Unmeasured, measured_by=router)
 │       0 whole ms -> no row
 └─ renew: ReserveStat(minute)  <- now counts that row's cost
close / failover
 └─ billUnsettled: only what is left after the last row

The settle hook runs on the lease's ticker before holding is taken (swap holds the session's mu while Move takes holding), and not on the first reservation, which leaseOf may make under mu. claim stays the one place that advances the "billed up to" mark, so each millisecond is billed once by a turn, a renewal or the close.

Stream Before After
no settled turn, credit spent runs to the end, billed at close refused after two renewals, rows as it goes
turns that settle before each renewal turn rows the same turn rows (no row for a sub-ms remainder)
vendor that measures itself turn rows unchanged (billUnsettled skips it)
customer's own key, free model, or moved to one by a failover turn rows unchanged (the lease checks the model's price at each tick)

The timing line's cost_micros keeps the cost of these rows: it now lives in streamedAudio (guarded by mu), since the renewal goroutine cannot touch forward's relay.

Changes

  • internal/routing/lease.go: StartLeaseEvery takes a settle func called before each renewal but the first, while a minute of the lease's current model costs anything (the check Move uses).
  • internal/sttrouter/session.go: leaseOf passes billUnsettled(nil); billUnsettled keeps the cost per provider.
  • internal/stsrouter/session.go: passes nil (no change).

Validation

New MoneySuite tests (real enforcer, internal/sttrouter/reserve_integration_test.go):

Test Catches On base
TestAStreamThatSettlesNoTurnEndsOnceItsAudioSpentTheCredit no renewal write; double bill fails (never refused)
TestTheRenewalAfterTheAudioSpentTheCreditIsRefused settle after the reserve fails
TestTurnsSettledBetweenRenewalsAreBilledAsTheyWere a 0 ms row; extra rows for settled turns passes, same rows (control)
TestAudioTakenAsTheLeaseRenewsIsBilledOnce renewal vs turns vs close race, billed once (-race) passes
TestAStreamOnTheCustomersOwnKeyWritesNoRowBeforeItEnds a zero-cost row at each renewal on the customer's key passes
TestAStreamMovedToAFreeModelWritesNoRowBeforeItEnds price checked only when the lease starts passes
TestAStreamThatSettlesNoTurnOnTheModelAFailoverLeasedEndsOnceItsAudioSpentTheCredit the lease a failover from a free model starts settles nothing fails (never refused)
TestAStreamThatSettlesNoTurnOnTheModelItsLeaseMovedToEndsOnceItsAudioSpentTheCredit Move drops settle fails (never refused)

TestTurnsSettledBetweenRenewalsAreBilledAsTheyWere renews by hand (leaseRenew an hour), so a turn that settles late cannot split a row.

billed now closes the writer before it reads, so it sums every row, not the first batch written.

Mutations, all killed: no settle call, settle nil guard, settle after renew, session passes nil, lease drops settle, close bills the total again, 0 ms row, renewal does not advance the mark, timing line drops the renewal cost (x2), settle on the first reservation (deadlocks a failover from a free model), no price check at the tick, price checked only at start, failover lease with nil settle, Move drops settle.

Suites run: sttrouter (unit + integration, MoneySuite also -race), routing (unit + TestReserveSuite), stsrouter (unit + integration), agent (unit + TestAgentMoneySuite).

🤖 Generated with Claude Code

kanat and others added 4 commits November 26, 2026 11:17
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
…spent the credit

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
… is refused

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

@kanat kanat left a comment

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

VERDICT: NO-GO

Security review, round 1, head 28055e9. One Should fix; the rest of the change holds.

Held up under probes on a scratch copy:

  • Billed exactly once: the renewal, turn, failover and close writes all claim the same counter under one lock.
  • A failed billing write still counts: the money gate is settled in memory before the row is queued, so the renewal refuses once the audio spent the credit, as the settled-turn path does.
  • A stream moved to a free model is not refused, and the audio before the move is billed on the paid one.
  • A vendor-metered provider writes no row at a renewal; no row is written for 0 ms.
  • No lock cycle between the renewal goroutine, Close, swap and Move; the new guard (the renewal write) fails the PR's tests when removed.
  • No new route, input to the network, SQL or shell, and no internal error text or secret added to a log or row.

Should fix: a stream on the customer's own key now writes a zero-cost row at every renewal, which the base writes only at close. See the inline comment.

Not this PR, noted for a ticket: audio can still be taken faster than real time until two renewals in a row are refused; this PR narrows that and does not bound it.

@kanat kanat left a comment

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

VERDICT: NO-GO

Round 1 review at 28055e9, merged onto current main (92fcbb8, clean). The draft has no CI run yet; CI runs at gh pr ready.

The core rule holds. claim is the only code that moves the "billed up to" mark, and it runs under s.mu, so a turn, a renewal and the close each claim different milliseconds. Shown by: sttrouter integration, -race x3 on TestMoneySuite|TestRefusalsSuite, and probes on a scratch copy. A failover bills each model's audio at that model's price, once (probes: free to paid, paid to a model at twice the price, paid to paid with no turn). The lock order holds: settle takes mu before holding and never inside it. Moving settle inside holding hangs TestASessionHoldsItsMinuteFromOneRenewalToTheNext. The stsrouter change passes nil and changes nothing there.

I agree with S1.1 (own-key lease). R1.3 is a second site of the same class.

Mutations: 6 reviewer mutants plus the author's 11. Two survive on the failover paths (R1.1).

Question R1.5 (author's question): stsrouter recordTrailing has the same shape: caller audio is billed only when a reply settles or the session ends. It is outside this PR, so file a ticket. TTS is not affected: it reserves each sentence before sending it.

Should fix: R1.1, R1.2, R1.3. Nit: R1.4.

Comment thread acceleration/internal/routing/lease.go Resolved
kanat and others added 4 commits November 26, 2026 12:20
… costs anything

A stream on the customer's own key, or moved to a free model, wrote a zero-cost row at every
renewal. The lease now checks the model it is on before each renewal's settle.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
…enewal window

The control renews by hand with no lease tick of its own, so a turn that settles late cannot be
split. The first-renewal test gets a second of margin and checks the audio was taken before it.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

@kanat kanat left a comment

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

VERDICT: NO-GO

Delta round 2, cd7be6fe8 merged onto main at 21b2551e4. R1.1, R1.2, R1.3 and S1.1 are fixed. One new Should fix: a mutant of the new per-tick check survives the PR's tests.

Prior findings

  • S1.1 (own-key stream wrote a zero-cost row at each renewal): fixed. Mutation settle without the bills() check: TestAStreamOnTheCustomersOwnKeyWritesNoRowBeforeItEnds fails.
  • R1.3 (stream moved to a free model kept writing rows): fixed. Same mutation: TestAStreamMovedToAFreeModelWritesNoRowBeforeItEnds fails.
  • R1.1 (failover and Move leases untested): fixed. Mutations: swap's new lease gets a nil settle: the three no-turn tests and the renewal-window test fail. Move drops settle: ...ItsLeaseMovedTo... fails.
  • R1.2 (control depended on a 500 ms window): fixed. The control now uses an hour-long renew and two direct billUnsettled(nil) calls. Mutation ms < 0 (0 ms row): the control fails. Mutation settle-after-renew: TestTheRenewalAfterTheAudioSpentTheCreditIsRefused fails (4.2 s against the 3 s bound).

Races (the lease's per-tick check)
bills() reads l.config under holding, the same lock Move writes it under, so it is race-free. A tick that reads the old model and then loses to Move bills at most one extra settle on rows the session prices per provider, and claim hands each millisecond to exactly one caller, so nothing is billed twice. A tick that reads a free model skips the settle, and the next tick bills the paid audio before its renewal. Probe: 400 alternating Move(free) / Move(paid) against 1 ms ticks and audio, -race -count=5: no race, billed total equals audio taken once.

New finding

  • [Should fix] A mutant that survives: a lease that skips one settle because its model was free or own-key, and then never settles again ("sticky off"), passes every test in the PR. The PR's free-to-paid test (...AFailoverLeased...) starts on a model that holds no lease, so the lease that Move carries from an own-key model to a paid one is not covered. That is the "move from a free model to a paid one" case: the paid audio would then never be billed at renewal. Add this row to TestMoneySuite (checked: passes on head x2, fails under the mutant with "Expected error ... no credit left but got nil"):
func (s *MoneySuite) TestAStreamThatLeftTheCustomersOwnKeyForAPaidModelEndsOnceItsAudioSpentTheCredit() {
	leaseRenew = 20 * time.Millisecond
	money := policytest.Start(s.T(), "sttrouter_reserve")
	owner := money.Owner(s.T(), 50_000)
	first := &lastWordsSTT{emitter: stt.NewEmitter(64)}
	next := &lastWordsSTT{emitter: stt.NewEmitter(64)}
	session := s.on(money, owner, ownKeyModel, first, next, otherModel)
	s.Require().NotNil(session.lease)
	for range 5 {
		s.Require().NoError(session.ProcessAudio(speech(1_000), stt.Participant{}))
		time.Sleep(30 * time.Millisecond) // several ticks on the own-key model first
	}
	s.failover(session, first)
	s.Require().ErrorIs(s.spoken(session), policy.ErrNoCredits, "the paid model's audio spent the credit")
	s.said(session)
	s.EqualValues(next.frames()*1_000, s.billedBy(money, owner)[otherModel.Model], "billed once")
}

The mutant: in keep, set a field off the first time bills() is false and skip settle while it is set.

  • [Nit] TestTheRenewalAfterTheAudioSpentTheCreditIsRefused still bounds the first refusal by wall-clock (2 s renew, refusal before 3 s): 1 s of margin, so it is not window-free under heavy load. The own-key and moved-to-free tests assert "no row", so on a machine too loaded for any tick to fire they would pass without testing anything. Neither blocks.

Runs
Integration (-p 1) sttrouter, routing, stsrouter: pass. Unit for the same three: pass. TestMoneySuite -race -count=3 and -cpu 1 -count=10: pass. CI on this draft: CodeQL, labeler, GitGuardian, Analyze pass; go and integration skipped (draft).

kanat and others added 3 commits November 26, 2026 12:52
…to a paid model still bills at renewal

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
…ck windows

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
@kanat

kanat commented Nov 26, 2026

Copy link
Copy Markdown
Collaborator Author

Round 2 fixes pushed: R2.1 (own-key-then-paid failover row added to MoneySuite; the sticky-off mutant now fails it) and R2.2 (renewal tests wait for counted renewals instead of wall-clock windows; the settle-after-renew and no-bills() mutants fail them).

@kanat kanat left a comment

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

VERDICT: GO

Delta round 3, reviewed 0f9f1af (merged onto origin/main b11e578). The delta is test-only: two commits in acceleration/internal/sttrouter/reserve_integration_test.go. The merge resolved nothing (git show --remerge-diff is empty).

Prior findings:

  • R2.1 (own key, failover to a paid model, sticky-off mutant): fixed. The new test fails under the mutant and passes on head.
  • R2.2 (wall-clock windows in the renewal tests): fixed. The renewal tests wait on the renewal count, and the first-refusal test asserts exactly one renewal ran. The settle-after-renew mutant and the no-bills() mutant are each killed.

Mutations (4 checked, 1 survived by one test and killed by five others):

  • sticky-off in routing/lease.go keep: killed by TestAStreamThatStartedOnTheCustomersOwnKeyAndFailedOverToAPaidModel....
  • settle after renew: killed by TestTheRenewalAfterTheAudioSpentTheCreditIsRefused.
  • no bills() check: killed by the own-key and moved-to-free tests.
  • skip the renewal write: killed by five tests; TestAudioTakenAsTheLeaseRenewsIsBilledOnce passes it (Nit below).

Head runs, integration, -p 1, on the merged head: TestMoneySuite and TestRefusalsSuite pass; TestMoneySuite passes 4 of 4 repeats.

New findings: none blocking.

  • Nit (reserve_integration_test.go:325): the first-refusal test assumes its 200 frames finish within the 2 s renewal period. A stall past 2 s fails the test loudly; it cannot pass vacuously.
  • Nit (reserve_integration_test.go:397): TestAudioTakenAsTheLeaseRenewsIsBilledOnce checks only the billed total, so it does not by itself show that renewals write rows. The tests above cover that.

Draft PR; CI does not run on drafts.

@kanat
kanat marked this pull request as ready for review November 26, 2026 18:03
@kanat
kanat merged commit b03fcde into main Nov 26, 2026
15 checks passed
@kanat
kanat deleted the kanat/ai-3857-bill-unsettled-audio-at-renewal branch November 26, 2026 19:02
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant